package com.one.shopping.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.one.shopping.R;
import com.one.shopping.api.OneApi;
import com.one.shopping.entity.Goods;
import com.one.shopping.entity.Result;
import com.one.shopping.ui.baseActivity.BaseActivity;
import com.one.shopping.util.AppConstant;
import com.one.shopping.util.CommonUtils;
import com.one.shopping.util.GsonUtils;
import com.one.shopping.util.Utils;

import org.apache.http.Header;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

/**
 * @author 柯尊诚
 * @version 1.0
 * @date 创建时间：2016/1/12 18:31
 */
public class AddGoodsActivity extends BaseActivity implements View.OnClickListener{

    private EditText idField;
    private EditText nameField;
    private EditText stockField;
    private EditText priceField;
    private Button submitBtn;
    private ImageView imageValues;
    private Button selectImageBtn;
    private ImageView scanBtn;
    private boolean isUpdate;
    private Goods goods;

    private static final String SCAN_INTENT = "com.google.zxing.client.android.SCAN";
    private static final String SCAN_RESULT = "SCAN_RESULT";

    @Override
    protected int getContentViewId() {
        return R.layout.add_goods_activity;
    }

    @Override
    protected void initView() {
        super.initView();

        idField = findView(R.id.add_goods_id_field_tv);
        nameField = findView(R.id.add_goods_name_field_tv);
        stockField = findView(R.id.add_goods_stock_field_tv);
        priceField = findView(R.id.add_goods_price_field_tv);
        imageValues = findView(R.id.add_goods_image_values_iv);
        selectImageBtn = findView(R.id.add_goods_image_select_btn);
        submitBtn = findView(R.id.add_goods_sumit_btn);
        scanBtn = findView(R.id.add_goods_scan_iv);
        goods = new Goods();
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        Goods goods = (Goods) intent.getSerializableExtra("goods");
        if (CommonUtils.isNullOrEmpty(goods)) {
            setTitle("添加商品");
        } else {
            setTitle("修改商品");
            isUpdate = true;
            idField.setText("" + goods.getId());
            nameField.setText(goods.getName());
            stockField.setText("" + goods.getStock());
            priceField.setText("" + goods.getPrice());
        }
    }

    @Override
    protected void initListener() {
        super.initListener();

        scanBtn.setOnClickListener(this);
        submitBtn.setOnClickListener(this);

        selectImageBtn.setOnClickListener(this);
    }

//    /**
//     * 点击提交按钮
//     */
//    private View.OnClickListener onClickSubmitListener = new View.OnClickListener() {
//        @Override
//        public void onClick(View view) {
//
//        }
//    };

    /**
     * 处理点击提交
     */
    private void onNextSubmit() {
        String id = idField.getText().toString().trim();
        String name = nameField.getText().toString().trim();
        int stock = Integer.parseInt(stockField.getText().toString().trim());
        double price = Double.parseDouble(priceField.getText().toString().trim());
        if (CommonUtils.isNullOrEmpty(id)) {
            nameField.setError("商品编号不能为空");
            return;
        }
        if (CommonUtils.isNullOrEmpty(name)) {
            nameField.setError("商品名称不能为空");
            return;
        }
        if (CommonUtils.isNullOrEmpty(stock)) {
            stockField.setError("库存量不能为空");
            return;
        }
        if (CommonUtils.isNullOrEmpty(price)) {
            stockField.setError("价格不能为空");
            return;
        }
        if (CommonUtils.isNullOrEmpty(imageValues)) {
            stockField.setError("商品图片不能为空");
            return;
        }


        goods.setId(id);
        goods.setName(name);
        goods.setStock(stock);
        goods.setPrice(String.valueOf(price));

        if (isUpdate) {
            OneApi.updateGoods(goods, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    Result result = GsonUtils.fromJson(new String(bytes), Result.class);
                    makeToast(result.getMessage());
                    finish();
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                    makeToast("网络错误！");
                }
            });
        } else {
            OneApi.addGoods(goods, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    Result result = GsonUtils.fromJson(new String(bytes), Result.class);
                    if (result.getCode() == 500) {
                        makeToast(result.getMessage());
                    } else {
                        makeToast(result.getMessage());
                        finish();
                    }
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                    makeToast("网络错误！");
                }
            });
        }
    }

    private void onNextScan() {
        Intent intentScan = new Intent(SCAN_INTENT);
        intentScan.addCategory(Intent.CATEGORY_DEFAULT);

        startActivityForResult(intentScan, 100);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描回调
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            String result = data.getStringExtra(SCAN_RESULT);

            Toast.makeText(getApplication(), result, Toast.LENGTH_SHORT).show();
            idField.setText(result);
        }

        //开始选择图片裁图
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (null == data) {
            return;
        }
        Uri uri = null;
        if (requestCode == AppConstant.KITKAT_LESS) {
            uri = data.getData();
            Log.d("tag", "uri=" + uri);
            //调用裁剪方法
            Utils.getInstance().cropPicture(this, uri);
        } else if (requestCode == AppConstant.KITKAT_ABOVE) {
            uri = data.getData();
            Log.d("tag", "uri=" + uri);
            //先将这个uri转换成path，然后再转换成uri
            String thePath = Utils.getInstance().getPath(this, uri);
            Utils.getInstance().cropPicture(this, Uri.fromFile(new File(thePath)));
        } else if (requestCode == AppConstant.INTENT_CROP) {
            Bitmap bitmap = data.getParcelableExtra("data");

            if(bitmap == null) {
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            imageValues.setImageBitmap(bitmap);
            selectImageBtn.setVisibility(View.GONE);
            imageValues.setVisibility(View.VISIBLE);
            File temp = new File(Environment.getExternalStorageDirectory().getPath() + "/yourAppCacheFolder/");//自己缓存文件夹
            if (!temp.exists()) {
                temp.mkdir();
            }
            String imageName = Calendar.getInstance().getTimeInMillis() + ".jpg";
            goods.setImage(imageName);
            String filePath = temp.getAbsolutePath() + "/" + imageName;
            File tempFile = new File(temp.getAbsolutePath() + "/" + imageName);//以时间秒为文件名
            //图片保存到文件中
            FileOutputStream foutput = null;
            try {
                foutput = new FileOutputStream(tempFile);
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, foutput)) {
                    Toast.makeText(AddGoodsActivity.this, "已生成缓存文件，等待上传！文件位置：" + tempFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                }
                Log.i("xxxxxxx", "xxxxxx");

//                upload(filePath);
                OneApi.uploadImage(AddGoodsActivity.this, filePath);


            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_goods_image_select_btn :
                Utils.getInstance().selectPicture(this);
                break;
            case R.id.add_goods_sumit_btn :
                onNextSubmit();
                break;
            case R.id.add_goods_scan_iv :
                onNextScan();
                break;
            default:
                break;
        }
    }


}
